package com.linkoog.devtools.code_generator.util;

import com.intellij.psi.PsiDirectory;
import org.apache.commons.lang3.StringUtils;

public class PsiDirectoryUtil {

    public static PsiDirectory createSubDirectory(PsiDirectory psiDirectory, String subPath) {
        if (StringUtils.isNotEmpty(subPath)) {
            if (subPath.startsWith("/")) {
                subPath = subPath.substring(1);
            }

            if (subPath.endsWith("/")) {
                subPath = subPath.substring(0, subPath.length() - 1);
            }

            String[] subPathAttr = subPath.split("/");
            return createSubDirectory(psiDirectory, subPathAttr, 0);
        } else {
            return psiDirectory;
        }
    }

    private static PsiDirectory createSubDirectory(PsiDirectory psiDirectory, String[] temp, int level) {
        PsiDirectory subdirectory = psiDirectory.findSubdirectory(temp[level]);
        if (subdirectory == null) {
            subdirectory = psiDirectory.createSubdirectory(temp[level]);
        }
        if (temp.length != level + 1) {
            return createSubDirectory(subdirectory, temp, level + 1);
        }
        return subdirectory;
    }
}
